package com.util;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Component {
	

	/**
	 * 过滤request(JSON除外)
	 */
	public static String getQuest(String str,HttpServletRequest request)
	{
		if(null==request.getParameter(str)||"".equals(request.getParameter(str))) return "";
		else return request.getParameter(str).replaceAll(".*([';]+|(--)+).*", " ");
	}
	
	/**
	 * 取session
	 */
	public static String getSession(String name,HttpServletRequest request)
	{
		return (String)request.getSession().getAttribute(name);
	}
	/*****************************************************
	 * 功能介绍:字符串转为unicode
	 * 输入参数:字符串
	 * 输出参数:unicode字符串
	 *****************************************************/
	public static String gbEncoding(String gbString ) {
	   char[] utfBytes = gbString.toCharArray();
	   String unicodeBytes = "";
	   for( int byteIndex = 0; byteIndex < utfBytes.length; byteIndex ++ ) {
	     String hexB = Integer.toHexString( utfBytes[ byteIndex ] );
	     if( hexB.length() <= 2 ) {
	        hexB = "00"+hexB;
	     }
	     unicodeBytes = unicodeBytes + "@" + hexB;
	   }

	  return unicodeBytes;
	}
	/*****************************************************
	 * 功能介绍:将unicode字符串转为汉字
	 * 输入参数:源unicode字符串
	 * 输出参数:转换后的字符串
	 *****************************************************/
	public static String UnicodeToGB2312(String str) {

	    String res = null;
	    StringBuffer sb = new StringBuffer();
	    try {
	    	
	      while (str.length() > 0) {
	        if (str.startsWith("@")) {

	          int x = Integer.parseInt(str.substring(1, 5), 16);
	          sb.append( (char) x);
	          str = str.substring(5);
	        }
	        else {
	          sb.append(str.charAt(0));
	          str = str.substring(1);
	        }
	      }
	      res = sb.toString();

	    }
	    catch (Exception e) {
	      System.err.println("in UnicodeToGB2312:" + e.toString());
	    }
	    
	    
	 
	    return res;
	  }

	public static String decodeBase64(byte data[])
	{
	    int len = data.length;
	    StringBuffer ret = new StringBuffer((len * 3) / 4);
	    for(int i = 0; i < len; i++)
	    {
	        int c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(data[i]);
	        i++;
	        int c1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(data[i]);
	        c = c << 2 | c1 >> 4 & 3;
	        ret.append((char)c);
	        if(++i < len)
	        {
	            c = data[i];
	            if(61 == c)
	                break;
	            c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf((char)c);
	            c1 = c1 << 4 & 0xf0 | c >> 2 & 0xf;
	            ret.append((char)c1);
	        }
	        if(++i >= len)
	            continue;
	        c1 = data[i];
	        if(61 == c1)
	            break;
	        c1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf((char)c1);
	        c = c << 6 & 0xc0 | c1;
	        ret.append((char)c);
	    }

	    return ret.toString();
	}
	public static String encodeBase64(byte data[])
	{
	    int len = data.length;
	    StringBuffer ret = new StringBuffer((len / 3 + 1) * 4);
	    for(int i = 0; i < len; i++)
	    {
	        int c = data[i] >> 2 & 0x3f;
	        ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
	        c = data[i] << 4 & 0x3f;
	        if(++i < len)
	            c |= data[i] >> 4 & 0xf;
	        ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
	        if(i < len)
	        {
	            c = data[i] << 2 & 0x3f;
	            if(++i < len)
	                c |= data[i] >> 6 & 3;
	            ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
	        } else
	        {
	            i++;
	            ret.append('=');
	        }
	        if(i < len)
	        {
	            c = data[i] & 0x3f;
	            ret.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c));
	        } else
	        {
	            ret.append('=');
	        }
	    }

	    return ret.toString();
	}
	
	
	/**
	 * 弹出对话框1
	 * @param nr  提示内容
	 * @param lx  弹出后转向类型0-返回原见面，1-关闭
	 * @return 
	 * @throws Exception
	 */
	public void message(String nr,String lx,HttpServletResponse response) throws Exception
	{
		 PrintWriter out = response.getWriter();
		 
		 if("0".equals(lx))
		 {
			 out.println("<SCRIPT LANGUAGE=\"JavaScript\">");
			 out.println("alert(\""+nr+"!\\n点击确认返回!\");");
			 out.println("javascript:history.back();");
			 out.println("</SCRIPT>");
			 out.flush();
			 out.close(); 
		 }
		 else if("1".equals(lx))
		 {
			 out.println("<SCRIPT LANGUAGE=\"JavaScript\">");
			 out.println("alert(\""+nr+"!\\n点击确认关闭!\");");
			 out.println("javascript:window.close();");
			 out.println("</SCRIPT>");
			 out.flush();
			 out.close(); 
			 
		 }
		
		 
	}



	/**
	 * 弹出对话框2
	 * @param nr  提示内容
	 * @param url  弹出后转向页面地址
	 * @throws Exception
	 */
	public static void messageUrl(String nr,String url,HttpServletResponse response) throws Exception
	{
		 PrintWriter out = response.getWriter();
	      out.print("<script>alert('"+nr+"')</script>" +
	      "<meta http-equiv='refresh' content='0; url="+url+"'>"); 

	}
	/**
	 * 弹出对话框3
	 * @param nr  提示内容
	 * @param url  框架页面跳转
	 * @throws Exception
	 */
	public static void messageUrlFrme(String nr,String url,HttpServletResponse response) throws Exception
	{
		 PrintWriter out = response.getWriter();
	      out.print("<script>alert('"+nr+"');window.parent.location='"+url+"';</script>");

	}
	
	
	/**
	 * 封装print打印
	 * @param o 对象名
	 * @param response
	 * @throws Exception
	 */
	public static void print(Object o,HttpServletResponse response) throws Exception
	{
		 PrintWriter out = response.getWriter();
	     out.print(o); 
	}


	/**
	 * 返回系统时间精确日(字符串)
	 * @return yyyy-MM-dd 
	 * @throws Exception
	 */
	public static String systime() throws Exception
	{
		 java.util.Date de =new Date();
		 java.text.DateFormat dated=new java.text.SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
		 String s_time=dated.format(de);
		 String id_temp;
		 id_temp=(s_time.substring(0,4) + '-'+ s_time.substring(5,7) + '-'+s_time.substring(8,10));		
	     return id_temp;
	}
	/**
	 * 返回系统时间精确到秒(字符串)
	 * @return yyyy-MM-dd HH:mm:ss 
	 * @throws Exception
	 */
	public static String systime_all() throws Exception
	{
		 java.util.Date de =new Date();
		 java.text.DateFormat dated=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String s_time=dated.format(de);	
	     return s_time;
	}
	
	 /**
     * 算2个日期之间的时间差天数（不含节假日）（日期格式yyyy-mm-dd）
	 * @param ssj 起始时间
	 * @param dsj 终止时间
	 * @return 返回天数
	 * @throws Exception
     */
//    public String SumtimeNew(String ssj,String dsj) throws Exception
//	{
//
//           Connection connect = null;
//           CallableStatement stmt = null;
//           int Action = 0;
//           String retn="";
//           try {
//    	      connect = this.dbAccess.getConnection();
//    	      stmt = connect.prepareCall("{?=call WF_GET_WORKDAY_DAYSJ(?,?)}");
//    	      // ---输入输出参数配置---
//    	      stmt.registerOutParameter(1, OracleTypes.NUMBER);
//    	      stmt.setString(2, ssj);
//    	      stmt.setString(3, dsj);
//    	      // 执行过程
//    	      stmt.execute();
//    	      // 返回日期
//    	       Action = stmt.getInt(1);
//    	       retn=String.valueOf(Action);
//    	     // DateFormat dated = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
//    	   
//             } catch (Exception ex) {
//
//    	     throw new Exception(ex);
//             } finally {
//    	     try {
//    		if (stmt != null) {
//    			stmt.close();
//    		}
//    		if (connect != null) {
//    			connect.close();
//    		}
//    	    } catch (Exception ex) {
//
//    		ex.printStackTrace();
//    	    }
//          }
//            return retn;
//
//          }
    
    
    /**
	 * 算2个日期之间的时间差天数（含节假日）（日期格式yyyy-mm-dd）
	 * @param ssj 起始时间
	 * @param dsj 终止时间
	 * @return 返回天数
	 * @throws Exception
	 */
    public static String Sumtime(String ssj,String dsj) throws Exception
	{
    	String time="";
    	long quot = 0; 
    	SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 
    	try 
		{ 
    	Date date1 = ft.parse( dsj ); 
    	Date date2 = ft.parse( ssj ); 
    	quot = date1.getTime() - date2.getTime(); 
    	quot = quot / 1000 / 60 / 60 / 24; 
    	time=String.valueOf(quot);
    	} catch (Exception e)
		{ 
    		time="时间逻辑有误";
    	} 
    	time=String.valueOf(Integer.parseInt(time)+1);
    	
    	return time; 
	}  
    
    
    /**
     * 获取两个时间差
     * @param rq1
     * @param rq2
     * @return
     * @throws Exception
     */
    public static  String getTimeAction(String rq1,String rq2) throws Exception
	{
		 String res="";
		 try
		 {
			 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 java.util.Date now = df.parse(rq1);
			 java.util.Date date=df.parse(rq2);
			 long l=now.getTime()-date.getTime();
			 long day=l/(24*60*60*1000);
			 long hour=(l/(60*60*1000)-day*24);
			 long min=((l/(60*1000))-day*24*60-hour*60);
			 long s=(l/1000-day*24*60*60-hour*60*60-min*60);
			 res=Math.abs(day)+"天"+Math.abs(hour)+"时"+Math.abs(min)+"分"+Math.abs(s)+"秒";
					
		 }catch(Exception ex)
		 {
			 res="0";
		 }
	
	  return res;
	}

    
    /**
     * 判断当天是否周6或周日（休息天）
     * @return
     */
	public static boolean is_FriDay(){
        java.util.Date de =new Date();
        java.util.Calendar ca = java.util.Calendar.getInstance();
        ca.setTime(de);
        System.out.println(ca.get(Calendar.DAY_OF_WEEK));
        if(ca.get(Calendar.DAY_OF_WEEK)==6||ca.get(Calendar.DAY_OF_WEEK)==7||ca.get(Calendar.DAY_OF_WEEK)==1){
            return true;
        }
        return false;
    }
	/**
	 * 判断字符串是否日期
	 * @param str
	 * @return
	 */
	public static boolean isValidDate(String str)
	  {      
		  boolean convertSuccess=true;
		  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		  try {
			  	format.setLenient(false);          
			  	format.parse(str);       
			  } catch (Exception e) {
				  convertSuccess=false;
			  }        
			  return convertSuccess;
		  
	   }

}
